<script>
  function reactiveArray(arr) {
    // DODO 数组
  }

  const targetMap = new WeakMap();
  let activeEffect;
  function reactive(obj) {
    if (typeof obj !== "object" || obj === null) {
      return obj;
    }
    if (Array.isArray(obj)) {
      return reactiveArray(obj);
    }
    const proxy = new Proxy(obj, {
      get(target, key, recevier) {
        let depMap = targetMap.get(target);
        if (!depMap) {
          depMap = new Map();
          targetMap.set(target, depMap);
        }
        let dep = depMap.get(key);
        if (!dep) {
          dep = new Set();
          depMap.set(key, dep);
        }
        if (activeEffect) {
          dep.add(activeEffect);
        }
        return Reflect.get(target, key, recevier);
      },
      set(target, key, value, recevier) {
        const depMap = targetMap.get(target);
        if (!depMap) {
          return Reflect.set(target, key, value, recevier);
        }
        const dep = depMap.get(key);
        const result = Reflect.set(target, key, value, recevier);
        if (dep) {
          dep.forEach((effect) => {
            effect();
          });
        }
        return result
      },
    });
    return proxy;
  }

  function watchEffect(fn) {
    if (activeEffect) return;
    activeEffect = fn;
    fn();
    activeEffect = null;
  }

  const person = reactive({
    name: "zhangsan",
    age: 18,
  });

  watchEffect(() => {
    console.log(person.name);
  });
  setTimeout(() => {
    person.name = "lisi";
  }, 1500);
</script>
